package net.nagaseyasuhito.nicola.entity;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Lob;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
public class Image extends BaseEntity {
	private static final long serialVersionUID = 1L;

	@Entity
	@Table(name = "Image_Store")
	public static class Store extends BaseEntity {
		private static final long serialVersionUID = 1L;

		@Column(nullable = false)
		@Lob
		private byte[] content;

		public byte[] getContent() {
			return content;
		}

		public void setContent(byte[] content) {
			this.content = content;
		}
	}

	@OneToOne(fetch = FetchType.LAZY)
	@Cascade(value = {CascadeType.ALL, CascadeType.DELETE_ORPHAN})
	private Store store;

	@Transient
	private transient BufferedImage cache;

	public BufferedImage getContent() throws IOException {
		if(this.cache != null) {
			return this.cache;
		}
		return this.cache = ImageIO.read(new ByteArrayInputStream(this.store.getContent()));
	}

	public void setContent(BufferedImage content) throws IOException {
		if(content == null) {
			this.setByteArray(null);
			return ;
		}

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(content, "png", out);

		this.setByteArray(out.toByteArray());
	}
	
	public void setByteArray(byte[] content) {
		this.cache = null;
		if(content == null) {
			this.store = null;
			return ;
		}

		this.store = new Store();
		this.store.setContent(content);
	}

	public byte[] getByteArray() {
		return this.store.getContent();
	}
}
